package com.qianguo.buyer;

import android.content.Context;
import android.content.Intent;

import com.eva.androidlibrary.api.HttpRequestCallback;
import com.eva.androidlibrary.api.entity.UserInfo;
import com.eva.androidlibrary.utils.ValidateUtil;
import com.eva.androidlibrary.widget.mdedittext.MaterialEditText;
import com.qianguo.buyer.base.BaseTitleActivity;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;


/**
 * 登陆页
 *
 * @author GUXIA318
 * @date 2015-09-23 14:13
 */
@EActivity(R.layout.activity_buyer_login)
public class BuyerLoginActivity extends BaseTitleActivity {

    @ViewById(R.id.login_mobile_edit_text)
    MaterialEditText mEdtMobile;
    @ViewById(R.id.login_password_edit_text)
    MaterialEditText mEdtPassword;

    public static void jumpToLogin(Context context) {
        context.startActivity(new Intent(context, BuyerLoginActivity_.class));
    }

    @Override
    protected String getToolbarTitle() {
        return getString(R.string.login);
    }

    @Override
    protected void initializeUI() {

    }

    /**
     * 找回密码
     */
    @Click(R.id.login_find_password_tv)
    void clickFindPsw() {
//        FindPasswordActivity.jumpToFindPsw(this);
    }

    /**
     * 登陆
     */
    @Click(R.id.login_button)
    void clickLogin() {
        String mobile = mEdtMobile.getText().toString();
        String password = mEdtPassword.getText().toString();
        if (validateInfo(mobile, password)) {
            login(mobile, password);
        }
    }

    /**
     * 后台登陆请求
     *
     * @param mobile
     * @param password
     */
    @Background
    void login(String mobile, String password) {
        mApp.getApi().login(mobile, password, 1, new HttpRequestCallback<UserInfo>() {
            @Override
            public void onSuccess(int code, String msg, UserInfo data) {
                UserManager.saveUser(mApp, data);
                EventBus.getDefault().post(data);
                finish();
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(BuyerLoginActivity.this, msg);
            }
        });
    }

    /**
     * 验证手机和密码的有效性
     *
     * @param mobile
     * @param password
     * @return
     */
    private boolean validateInfo(String mobile, String password) {
        if (!ValidateUtil.isChinesePhoneNumber(mobile)) {
            mEdtMobile.setError(getString(R.string.edit_error_mobile));
            return false;
        }

        if (password.length() < 6 || password.length() > 20) {
            mEdtPassword.setError(getString(R.string.edit_error_password));
            return false;
        }

        return true;
    }
}
